
// type ChannelCallback = (...args: any) => any;
// type ChannelCallbacks = Array<ChannelCallback>;


/**
 * new Map<string, ChannelCallbacks>();
 */
const channelsMap = new Map();

/**
 * 事件
 */
export class EventService {

  /**
   * 订阅
   *
   * @param {string} eventName 事件名称
   * @param {function} callbackFn 回调函数
   * @returns {ChannelCallbacks}
   */
  static subscribe(eventName, callbackFn) {
    const callbacks = channelsMap.get(eventName) || [];
    const hasFn = !!~callbacks.findIndex(cb => cb === callbackFn);
    if (!hasFn) {
      callbacks.push(callbackFn);
      channelsMap.set(eventName, callbacks);
    }
    return callbacks;
  }

  /**
   * 取消订阅
   *
   * @param {string} eventName 事件名称
   *
   * @return true if a handler was removed
   */
  static unsubscribe(eventName) {
    return channelsMap.delete(eventName);
  }

  /**
   * 销毁
   */
  static destroy() {
    channelsMap.clear();
  }

  /**
   * 发布
   *
   * @param {string} eventName 事件名称
   * @param {any} eventData 事件发送数据
   * @returns {ChannelCallbacks}
   */
  static publish(eventName, ...eventData) {
    const callbacks = channelsMap.get(eventName) ?? [];
    callbacks.forEach(cb => {
      cb(...eventData);
    })
    return callbacks;
  }
}